<template>
  <div style="position:absolute;" :style="calcToolStyle">
    <DataGridViewToolTip></DataGridViewToolTip>
  </div>
  <div
    v-menus:right="menusOtions" style="position:absolute;" :style="calcStyle"
    @mouseup="handleSelectCellMouseUp"
  >
    <template v-for="(cell, index) in gridView.Cells" :key="index">
      <DataGridViewCell
        :cell="cell" :table-index="tableIndex" @click="handleSelectCell(cell)" @mousedown="(e)=>handleSelectCellMouseDown(e,cell)"
        @dblclick="handleEditCell(cell)" @mouseenter="handleSelectCellMouseEnter(cell)"
      >
      </DataGridViewCell>
    </template>

  </div>
</template>
<script>
import DataGridViewCell from './DataGridViewCell.vue';
import DataGridViewToolTip from './DataGridViewToolTip.vue';
import { computed, ref } from 'vue';

export default {
  components: { DataGridViewCell, DataGridViewToolTip },
  provide() {
    return {
      gridView: computed(() => this.gridView),
    };
  },
  inject: ['manager'],
  props: {
    tableIndex: {
      type: Number,
      default: 0,
    },
  },
  setup() {
    const startCell = ref({});
    const endCell = ref({});
    return {
      startCell,
      endCell,
    };
  },
  data() {
    return {
      // 单元格的二维数组
      // showCells: [],
      isMultiple: false,
      contextMenuVisible: false,
      menusOtions: {
        menus: [

          { label: '合并单元格', click: () => { this.menuClick('MergeCell'); } },
          { label: '拆分单元格', click: () => { this.menuClick('SplitCell'); } },
          {
            label: '添加行',
            children: [
              { label: '添加行-上方', click: () => { this.menuClick('Up'); } },
              { label: '添加行-下方', click: () => { this.menuClick('Down'); } },
              { label: '添加行-左侧', click: () => { this.menuClick('Left'); } },
              { label: '添加行-右侧', click: () => { this.menuClick('Right'); } },

              { label: '添加标题行', click: () => { this.menuClick('Title'); } },
              { label: '添加列头行', click: () => { this.menuClick('ColumnHeader'); } },
              { label: '添加明细行', click: () => { this.menuClick('Detail'); } },
              { label: '添加列脚行', click: () => { this.menuClick('ColumnFooter'); } },
              { label: '添加摘要行', click: () => { this.menuClick('Summary'); } },

            ],
          },
          { label: '删除行', click: () => { this.menuClick('DeleteRow'); } },
          { label: '删除列', click: () => { this.menuClick('DeleteColumn'); } },
          { label: '删除表格', click: () => { this.menuClick('deleteTable'); } },

        ],
        zIndex: 999,
      },
    };
  },
  computed: {
    gridView() {
      return this.manager.Body.AllGridViews[this.tableIndex];
    },
    gridViewHeight() {
      let val = 0;
      this.gridView.Rows.forEach(a => {
        val += a.Height;
      });
      return val;
    },
    gridViewWidth() {
      let val = 0;
      this.gridView.Columns.forEach(a => {
        val += a.Width;
      });
      return val;
    },
    calcStyle() {
      const obj = {
        height: this.gridViewHeight + 'px',
        width: this.gridViewWidth + 'px',
        left: this.gridView.Left + 'px',
        top: this.gridView.Top + 'px',
        border: '1px dotted #cddaea',
        'z-index': this.gridView.ZIndex,
      };

      if (this.tableIndex === this.manager.states.tableIndex) {
        obj.border = '1px dotted #FF9933';
      }

      return obj;
    },
    calcToolStyle() {
      const obj = {
        height: this.gridViewHeight + 'px',
        width: '20' + 'px',
        left: this.gridView.Left - 30 + 'px',
        top: this.gridView.Top + 'px',
        'z-index': this.gridView.ZIndex,
      };
      if (this.tableIndex !== this.manager.states.tableIndex) {
        obj.display = 'none';
      }

      return obj;
    },
  },
  watch: {
    // gridView() {

    // },
  },
  mounted() {
    // const array = [1, 2, 3, 4, 5];
    // array.splice(1, 0, 9);
    // console.log(array);
    // this.init();
  },
  methods: {
    // init() {
    //   this.initCells();
    // },

    menuClick(type) {
      this.$nextTick(() => {
        if (type === 'deleteTable') {
          this.manager.deleteTable();
        } else if (type === 'Up') {
          this.addUpDownRow(false);
        } else if (type === 'Down') {
          this.addUpDownRow(true);
        } else if (type === 'Left') {
          this.addLeftRightColumn(false);
        } else if (type === 'Right') {
          this.addLeftRightColumn(true);
        } else if (type === 'MergeCell') {
          this.mergeCell();
        } else if (type === 'SplitCell') {
          this.splitCell();
        } else if (type === 'DeleteRow') {
          this.DeleteRow();
        } else if (type === 'DeleteColumn') {
          this.DeleteColumn();
        } else {
          this.addRowByType(type);
        }
      });
    },

    handleSelectCell(cell) {
      // 点击单选
      this.manager.states.visibleCells = [cell];
      this.manager.states.currentCell = cell;
    },
    handleEditCell(cell) {
      this.manager.states.visibleCells = [cell];
      this.manager.states.currentCell = cell;
      this.manager.expCallBack = this.expCallBack;
      this.manager.states.EditExpression = cell.Text;

      this.manager.states.EditExpressionVisible = true;
    },
    expCallBack(pim, psm, param) {
      this.manager.states.currentCell.Text = pim;
      this.manager.states.currentCell.CellPsm = psm;
      this.manager.states.currentCell.CellParam = param;
    },
    handleSelectCellMouseDown(e, cell) {
      // 判断 cell 是否在 visibleCells 中
      const flag = this.manager.states.visibleCells.find(a => a.RowIndex === cell.RowIndex && a.ColumnIndex === cell.ColumnIndex);
      if (!flag) {
        this.isMultiple = true;
        this.startCell = cell;
        this.manager.states.tableIndex = this.tableIndex;
        this.manager.states.visibleCells = [cell];
        this.manager.states.currentCells = [cell];
      }
    },
    handleSelectCellMouseUp() {
      this.isMultiple = false;
    },
    handleSelectCellMouseEnter(cell) {
      if (this.isMultiple && this.manager.states.tableIndex === this.tableIndex) {
        this.endCell = cell;

        const minRowIndex = this.startCell.RowIndex >= this.endCell.RowIndex ? this.endCell.RowIndex : this.startCell.RowIndex;
        const maxRowIndex = this.startCell.MaxRowIndex > this.endCell.MaxRowIndex ? this.startCell.MaxRowIndex : this.endCell.MaxRowIndex;

        const minColIndex = this.startCell.ColumnIndex >= this.endCell.ColumnIndex ? this.endCell.ColumnIndex : this.startCell.ColumnIndex;
        const maxColIndex = this.startCell.MaxColumnIndex > this.endCell.MaxColumnIndex ? this.startCell.MaxColumnIndex : this.endCell.MaxColumnIndex;

        this.manager.states.visibleCells = [];

        for (let i = 0; i < this.gridView.Cells.length; i++) {
          if (this.gridView.Cells[i].RowIndex >= minRowIndex && this.gridView.Cells[i].RowIndex <= maxRowIndex &&
            this.gridView.Cells[i].ColumnIndex >= minColIndex && this.gridView.Cells[i].ColumnIndex <= maxColIndex) {
            this.manager.states.currentCells.push(this.gridView.Cells[i]);
            if (this.gridView.Cells[i].RowIndex === this.gridView.Cells[i].StartCellRowIndex &&
              this.gridView.Cells[i].ColumnIndex === this.gridView.Cells[i].StartCellColumnIndex) {
              this.manager.states.visibleCells.push(this.gridView.Cells[i]);
            }
          }
        }
      }
    },
    addUpDownRow(flag) {
      let RowIndex = this.manager.states.visibleCells[0].RowIndex;
      const rows = this.gridView.Rows;
      const type = rows[RowIndex].Type;
      if (flag) {
        RowIndex = this.manager.states.visibleCells[0].MaxRowIndex;
        // 下方加一行
        RowIndex++;
      }
      this.addRow(RowIndex, type);
    },
    addRow(RowIndex, type) {
      const newRow = { RowIndex: RowIndex, Height: 36, Type: type };
      // 处理历史行 加1
      for (let i = RowIndex; i < this.gridView.Rows.length; i++) {
        this.gridView.Rows[i].RowIndex++;
      }

      // 先在Rows里面新增
      let isLast = false;
      if (RowIndex === this.gridView.Rows.length) {
        isLast = true;
      }

      if (isLast) {
        this.gridView.Rows.push(newRow);
      } else {
        this.gridView.Rows.splice(RowIndex, 0, newRow);
        // 处理历史单元格 加1
        for (let i = 0; i < this.gridView.Cells.length; i++) {
          if (this.gridView.Cells[i].RowIndex >= RowIndex) {
            this.gridView.Cells[i].RowIndex++;
          }
          if (this.gridView.Cells[i].StartCellRowIndex >= RowIndex) {
            this.gridView.Cells[i].StartCellRowIndex++;
          }
          if (this.gridView.Cells[i].MaxRowIndex >= RowIndex) {
            this.gridView.Cells[i].MaxRowIndex++;
          }
        }
      }

      const newCells = [];
      for (let i = 0; i < this.gridView.Columns.length; i++) {
        const ColumnIndex = this.gridView.Columns[i].ColumnIndex;

        const obj = {
          RowIndex: RowIndex,
          ColumnIndex: ColumnIndex,
          StartCellRowIndex: RowIndex,
          StartCellColumnIndex: ColumnIndex,
          MaxRowIndex: RowIndex,
          MaxColumnIndex: ColumnIndex,
        };
        // if (RowIndex !== 0 || !isLast) {
        //   const preCell = this.gridView.Cells.find(a => a.RowIndex === RowIndex - 1 && a.ColumnIndex === ColumnIndex);
        //   const nextcell = this.gridView.Cells.find(a => a.RowIndex === RowIndex + 1 && a.ColumnIndex === ColumnIndex);

        //   if (preCell.StartCellColumnIndex === nextcell.StartCellColumnIndex) {
        //     obj.StartCellColumnIndex = preCell.StartCellColumnIndex;
        //   }
        //   if (preCell.StartCellRowIndex === nextcell.StartCellRowIndex) {
        //     obj.StartCellRowIndex = preCell.StartCellRowIndex;
        //   }
        // }
        const cell = this.manager.addNewCell(obj);
        newCells.push(cell);
      }

      if (isLast) {
        this.gridView.Cells.push(...newCells);
      } else {
        const insertAt = this.gridView.Cells.findIndex(a => {
          return a.RowIndex === RowIndex + 1 && a.ColumnIndex === 0;
        });
        // 这里是整体插入
        this.gridView.Cells.splice(insertAt, 0, ...newCells);
      }
    },
    addLeftRightColumn(flag) {
      let ColumnIndex = this.manager.states.visibleCells[0].ColumnIndex;
      if (flag) {
        ColumnIndex = this.manager.states.visibleCells[0].MaxColumnIndex;
        // 右侧加一列
        ColumnIndex++;
      }
      // 这里需要判断是否是新增的最后一列
      let isLast = false;
      if (ColumnIndex === this.gridView.Columns.length) {
        isLast = true;
      }
      const newCol = { ColumnIndex: ColumnIndex, Width: 72 };
      // 处理历史列 加1
      for (let i = ColumnIndex; i < this.gridView.Columns.length; i++) {
        this.gridView.Columns[i].ColumnIndex++;
      }
      if (isLast) {
        this.gridView.Columns.push(newCol);
      } else {
        this.gridView.Columns.splice(ColumnIndex, 0, newCol);
        // 处理历史单元格 加1
        for (let i = 0; i < this.gridView.Cells.length; i++) {
          if (this.gridView.Cells[i].ColumnIndex >= ColumnIndex) {
            this.gridView.Cells[i].ColumnIndex++;
          }
          if (this.gridView.Cells[i].StartCellColumnIndex >= ColumnIndex) {
            this.gridView.Cells[i].StartCellColumnIndex++;
          }
          if (this.gridView.Cells[i].MaxColumnIndex >= ColumnIndex) {
            this.gridView.Cells[i].MaxColumnIndex++;
          }
        }
      }

      // 新增
      for (let i = 0; i < this.gridView.Rows.length; i++) {
        const RowIndex = this.gridView.Rows[i].RowIndex;

        const obj = {
          Height: this.gridView.Rows[i].Height,
          Width: 36,
          RowIndex: RowIndex,
          ColumnIndex: ColumnIndex,
          StartCellRowIndex: RowIndex,
          StartCellColumnIndex: ColumnIndex,
          MaxRowIndex: RowIndex,
          MaxColumnIndex: ColumnIndex,
        };

        // 开始与结束不考虑合并
        // if (ColumnIndex !== 0 && !isLast) {
        //   const preCell = this.gridView.Cells.find(a => a.RowIndex === RowIndex && a.ColumnIndex === ColumnIndex - 1);
        //   const nextcell = this.gridView.Cells.find(a => a.RowIndex === RowIndex && a.ColumnIndex === ColumnIndex + 1);
        //   if (preCell.StartCellRowIndex === nextcell.StartCellRowIndex) {
        //     obj.StartCellRowIndex = preCell.StartCellRowIndex;
        //   }

        //   if (preCell.StartCellColumnIndex === nextcell.StartCellColumnIndex) {
        //     obj.StartCellColumnIndex = preCell.StartCellColumnIndex;
        //   }
        // }
        const cell = this.manager.addNewCell(obj);

        if (isLast) {
          // 如果是最后一列 需要找到下一列的第一列
          const insertAt = this.gridView.Cells.findIndex(a => {
            return a.ColumnIndex === 0 && a.RowIndex === RowIndex + 1;
          });
          // 没找到这里说明是最后一个
          if (insertAt === -1) {
            this.gridView.Cells.push(cell);
          } else {
            this.gridView.Cells.splice(insertAt, 0, cell);
          }
        } else {
          const insertAt = this.gridView.Cells.findIndex(a => {
            return a.ColumnIndex === ColumnIndex + 1 && a.RowIndex === RowIndex;
          });
          this.gridView.Cells.splice(insertAt, 0, cell);
        }
      }
    },
    addRowByType(type) {
      // 获取当前类型的 rowIndex
      let rowIndex = 0;
      if (type === 'Title') {
        rowIndex = this.gridView.Rows.filter(a => a.Type === 'Title').length;
      } else if (type === 'ColumnHeader') {
        rowIndex = this.gridView.Rows.filter(a => a.Type === 'Title' || a.Type === 'ColumnHeader').length;
      } else if (type === 'Detail') {
        rowIndex = this.gridView.Rows.filter(a => a.Type === 'Title' || a.Type === 'ColumnHeader' || a.Type === 'Detail').length;
      } else if (type === 'ColumnFooter') {
        rowIndex = this.gridView.Rows.filter(a => a.Type === 'Title' || a.Type === 'ColumnHeader' || a.Type === 'Detail' || a.Type === 'ColumnFooter').length;
      } else {
        rowIndex = this.gridView.Rows.length;
      }
      this.addRow(rowIndex, type);
    },
    mergeCell(flag) {
      // 获取选中的最大与最小
      let minRowIndex = 0;
      let maxRowIndex = 0;
      let minColumnIndex = 0;
      let maxColumnIndex = 0;
      for (let i = 0; i < this.manager.states.visibleCells.length; i++) {
        const cell = this.manager.states.visibleCells[i];
        if (i === 0) {
          minRowIndex = cell.RowIndex;
          minColumnIndex = cell.ColumnIndex;
          maxRowIndex = cell.MaxRowIndex;
          maxColumnIndex = cell.MaxColumnIndex;
        } else {
          if (minRowIndex > cell.RowIndex) {
            minRowIndex = cell.RowIndex;
          }
          if (minColumnIndex > cell.ColumnIndex) {
            minColumnIndex = cell.ColumnIndex;
          }
          if (maxRowIndex < cell.MaxRowIndex) {
            maxRowIndex = cell.MaxRowIndex;
          }
          if (maxColumnIndex < cell.MaxColumnIndex) {
            maxColumnIndex = cell.MaxColumnIndex;
          }
        }
        cell.MaxRowIndex = cell.RowIndex;
        cell.MaxColumnIndex = cell.ColumnIndex;
      }

      const minCell = this.gridView.Cells.find(a => a.RowIndex === minRowIndex && a.ColumnIndex === minColumnIndex);
      this.manager.states.visibleCells.forEach(a => {
        a.StartCellRowIndex = minCell.RowIndex;
        a.StartCellColumnIndex = minCell.ColumnIndex;
      });
      minCell.MaxRowIndex = maxRowIndex;
      minCell.MaxColumnIndex = maxColumnIndex;
    },
    splitCell() {
      const cell = this.manager.states.visibleCells[0];
      const minRowIndex = cell.RowIndex;
      const maxRowIndex = cell.MaxRowIndex;
      const minColumnIndex = cell.ColumnIndex;
      const maxColumnIndex = cell.MaxColumnIndex;
      for (let i = 0; i < this.gridView.Cells.length; i++) {
        if (this.gridView.Cells[i].RowIndex >= minRowIndex && this.gridView.Cells[i].RowIndex <= maxRowIndex &&
        this.gridView.Cells[i].ColumnIndex >= minColumnIndex && this.gridView.Cells[i].ColumnIndex <= maxColumnIndex) {
          this.gridView.Cells[i].MaxRowIndex = this.gridView.Cells[i].RowIndex;
          this.gridView.Cells[i].MaxColumnIndex = this.gridView.Cells[i].ColumnIndex;
          this.gridView.Cells[i].StartCellRowIndex = this.gridView.Cells[i].RowIndex;
          this.gridView.Cells[i].StartCellColumnIndex = this.gridView.Cells[i].ColumnIndex;
        }
      }
    },
    DeleteRow() {
      const cell = this.manager.states.visibleCells[0];
      const RowIndex = cell.RowIndex;
      const cells = this.gridView.Cells.filter(a => a.RowIndex === RowIndex);
      const cellCheck = cells.find(a => a.RowIndex !== a.MaxRowIndex || a.RowIndex !== a.StartCellRowIndex);
      if (cellCheck) {
        this.$message({
          type: 'error',
          message: '错误单元格' + cellCheck.RowIndex + ',' + cellCheck.ColumnIndex + '跨多行',
        });
        return;
      }
      // 删除行
      // 删除这行的单元格
      const colCount = this.gridView.Columns.length;
      const firstColumnIndex = this.gridView.Cells.findIndex(a => a.RowIndex === RowIndex && a.ColumnIndex === 0);
      this.gridView.Cells.splice(firstColumnIndex, colCount);
      // 重新赋值RowIndex
      this.gridView.Cells.forEach(a => {
        if (a.RowIndex > RowIndex) {
          a.RowIndex--;
        }
        if (a.MaxRowIndex > RowIndex) {
          a.MaxRowIndex--;
        }
        if (a.StartCellRowIndex > RowIndex) {
          a.StartCellRowIndex--;
        }
      });

      for (let i = RowIndex + 1; i < this.gridView.Rows.length; i++) {
        this.gridView.Rows[i].RowIndex--;
      }
      this.manager.clearStates();
      this.gridView.Height -= this.gridView.Rows[RowIndex].Height;
      this.gridView.Rows.splice(RowIndex, 1);
    },
    DeleteColumn() {
      const cell = this.manager.states.visibleCells[0];
      const ColumnIndex = cell.ColumnIndex;
      const cells = this.gridView.Cells.filter(a => a.ColumnIndex === ColumnIndex);
      const cellCheck = cells.find(a => a.ColumnIndex !== a.MaxColumnIndex || a.ColumnIndex !== a.StartCellColumnIndex);
      if (cellCheck) {
        this.$message({
          type: 'error',
          message: '错误单元格' + cellCheck.RowIndex + ',' + cellCheck.ColumnIndex + '跨多列',
        });
        return;
      }
      // 删除列
      // 删除这列的单元格
      // 重新赋值RowIndex
      const delIndex = [];
      for (let i = 0; i < this.gridView.Cells.length; i++) {
        if (this.gridView.Cells[i].ColumnIndex === ColumnIndex) {
          delIndex.push(i);
        }
        if (this.gridView.Cells[i].ColumnIndex > ColumnIndex) {
          this.gridView.Cells[i].ColumnIndex--;
        }
        if (this.gridView.Cells[i].MaxColumnIndex > ColumnIndex) {
          this.gridView.Cells[i].MaxColumnIndex--;
        }
        if (this.gridView.Cells[i].StartCellColumnIndex > ColumnIndex) {
          this.gridView.Cells[i].StartCellColumnIndex--;
        }
      }
      for (let i = 0; i < delIndex.length; i++) {
        this.gridView.Cells.splice(delIndex[i] - i, 1);
      }

      for (let i = ColumnIndex + 1; i < this.gridView.Columns.length; i++) {
        this.gridView.Columns[i].ColumnIndex--;
      }
      this.manager.clearStates();
      this.gridView.Width -= this.gridView.Columns[ColumnIndex].Width;
      this.gridView.Columns.splice(ColumnIndex, 1);
    },

  },
};
</script>
<style>
</style>
